/*
 * Copyright (c) 2019-2020, https://api.iot.10086.cn/(https://gitee.com/cmcc-iot-api/iot-card-open-application/).
 */
package cn.iot.card.open.terminal.controller;

import cn.iot.card.open.annotion.Permission;
import cn.iot.card.open.constants.Constants;
import cn.iot.card.open.context.LoginContextHolder;
import cn.iot.card.open.context.model.LoginUser;
import cn.iot.card.open.modular.entity.Card;
import cn.iot.card.open.modular.entity.UserGroupRl;
import cn.iot.card.open.modular.service.CardService;
import cn.iot.card.open.modular.service.GroupService;
import cn.iot.card.open.pojo.page.LayuiPageFactory;
import cn.iot.card.open.terminal.dto.SmsReceiveRecordDTO;
import cn.iot.card.open.terminal.service.SmsReceiveService;
import cn.iot.card.open.terminal.warpper.SmsReceiveWrapper;
import cn.iot.card.open.util.CommonUtil;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 短信上行
 *
 * @author cmcc-iot-api
 * @date 20201026 14:11:04
 */
@Controller
@RequestMapping("/terminalCtrl/smsReceive")
@Slf4j
public class SmsReceiveController {

    /**
     * 短信接收页面路径地址前缀
     */
    private static String PREFIX = "/modular/terminal/smsReceive";

    @Autowired
    private CardService cardService;

    @Autowired
    private GroupService groupService;

    @Autowired
    private SmsReceiveService smsReceiveService;

    /**
     * 跳转到短信上行查询列表页面
     *
     * @return 返回 string
     * @author cmcc-iot-api
     * @date 20201026 14:13:35
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/smsReceive.html";
    }

    /**
     * 查询短信下发记录
     *
     * @param smsReceiveRecordDTO
     * @return 返回 object
     * @throws Exception
     * @author cmcc-iot-api
     * @date 20201026 14:29:11
     */
    @Permission
    @RequestMapping("/list")
    @ResponseBody
    public Object list(SmsReceiveRecordDTO smsReceiveRecordDTO) throws Exception {
        String transId = CommonUtil.generateTransId(null);
        log.info("[{}] start get sms receive list.", transId);
        long startTime = System.currentTimeMillis();
        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = groupService.getUserGroupRlByUserId(loginUser.getId());
        // 如果当前用户未绑定卡组，则返回空（也可以提示错误）
        if (null == userGroupRl) {
            log.info("[{}] get sms receive list end, cost: {}ms.", transId, System.currentTimeMillis() - startTime);
            return LayuiPageFactory.createEmptyPageInfo();
//            return LayuiPageFactory.createBizExceptionMsg(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }

        String msisdn = smsReceiveRecordDTO.getMsisdn();
        List<Card> cardInGroups = cardService.findCardInGroup(userGroupRl.getGroupId().toString(),
                Constants.CARD_TYPE_MSISDN, StringUtils.isBlank(msisdn) ? null : msisdn);

        // 如果当前用户绑定的卡组下面没有任何卡，则返回空（也可以提示错误）
        if (ToolUtil.isEmpty(cardInGroups)) {
            log.info("[{}] get sms receive list end, cost: {}ms.", transId, System.currentTimeMillis() - startTime);
            return LayuiPageFactory.createEmptyPageInfo();
            //            return LayuiPageFactory.createBizExceptionMsg(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }
        String[] msisdns = new String[cardInGroups.size()];
        int cardNum = 0;
        for (Card card : cardInGroups) {
            msisdns[cardNum] = card.getMsisdn();
            cardNum ++;
        }

        Page<Map<String, Object>> accounts = smsReceiveService.selectSmsReceiveRecord(msisdns, smsReceiveRecordDTO);
        Page wrapped = new SmsReceiveWrapper(accounts).wrap();
        log.info("[{}] get sms receive list end, cost: {}ms.", transId, System.currentTimeMillis() - startTime);
        return LayuiPageFactory.createPageInfo(wrapped);

    }
}
